import React, { memo, useCallback, useMemo } from 'react';
import { LayoutChangeEvent } from 'react-native';
import Animated, { useAnimatedStyle } from 'react-native-reanimated';
import { KEYBOARD_STATE } from '../../constants';
import { useAdaptiveSheetInternal } from '../../hooks';
import type { AdaptiveSheetDefaultFooterProps } from './types';
import { styles } from './styles';

function AdaptiveSheetFooterComponent({ animatedFooterPosition, bottomInset = 0, style, children }: AdaptiveSheetDefaultFooterProps): JSX.Element {
  const { animatedFooterHeight, animatedKeyboardState } = useAdaptiveSheetInternal();

  const containerAnimatedStyle = useAnimatedStyle(() => {
    let footerTranslateY = animatedFooterPosition.value;

    // 仅在键盘未显示时偏移底部间距
    if (animatedKeyboardState.value !== KEYBOARD_STATE.SHOWN) {
      footerTranslateY = footerTranslateY - bottomInset;
    }

    return {
      transform: [
        {
          translateY: Math.max(0, footerTranslateY),
        },
      ],
    };
  }, [bottomInset, animatedKeyboardState, animatedFooterPosition]);
  const containerStyle = useMemo(() => [styles.container, style, containerAnimatedStyle], [style, containerAnimatedStyle]);

  const handleContainerLayout = useCallback(
    ({
      nativeEvent: {
        layout: { height },
      },
    }: LayoutChangeEvent) => {
      animatedFooterHeight.value = height;
    },
    [animatedFooterHeight],
  );

  return children !== null ? (
    <Animated.View pointerEvents="box-none" onLayout={handleContainerLayout} style={containerStyle}>
      {typeof children === 'function' ? children() : children}
    </Animated.View>
  ) : null;
}

const AdaptiveSheetFooter = memo(AdaptiveSheetFooterComponent);
AdaptiveSheetFooter.displayName = 'AdaptiveSheetFooter';

export default AdaptiveSheetFooter;
